package com.yilin.tms.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yilin.commons.exception.BusinessException;
import com.yilin.tms.core.entity.user.organize.Department;
import com.yilin.tms.core.entity.user.account.Account;
import com.yilin.tms.user.service.IDepartmentService;
import com.yilin.tms.user.mapper.DepartmentMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @author liuxu :)
 * @version 1.0
 * @date 2022-10-27
 */
@Service
public class DepartmentService extends ServiceImpl<DepartmentMapper, Department> implements IDepartmentService {
    @Resource
    DepartmentMapper departmentMapper;
    @Resource
    AccountService userAccountService;

    @Override
    public Department saveOrUpdateDepartment(Department department) {
        if (department.getId() != null) {
            department.setUpdateTime(new Date());
            departmentMapper.updateById(department);
        } else {
            department.setCreateTime(new Date());
            departmentMapper.insert(department);
        }
        return department;
    }

    @Override
    public void deleteDepartment(Department department) {
        if (department.getId() == null) {
            throw new BusinessException("部门id为空");
        }
        List<Account> accountList = userAccountService.getAccountList(department.getId());
        for (Account account : accountList) {
            account.setDepartmentId(null);
            account.setDepartmentName(null);
        }
        userAccountService.saveOrUpdateBatch(accountList);
        departmentMapper.deleteById(department);
    }

    @Override
    public List<Department> getDepartmentList(String organizeId) {
        List<Department> departmentList = departmentMapper.selectList(new QueryWrapper<Department>().eq("parent_organize", organizeId));
        if (departmentList == null) return null;
        for (Department department : departmentList) {
            List<Account> accountList = userAccountService.getAccountList(department.getId());
            for (Account account : accountList){
                account.setPassword(null);
                account.setDeviceId(null);
            }
            department.setStaffList(accountList);
        }

        return departmentList;
    }
}
